<template>
	<view>
		<view style="padding: 20rpx 40rpx;">
			<u--form labelPosition="left" :model="registerParams" ref="uForm" labelWidth='95' labelAlign='right'>
				<u-form-item label="姓名：" borderBottom ref="item1">
					<u--input name="姓名" required placeholder="姓名" v-model="registerParams.memberName"
						input-align="right" />
				</u-form-item>
				<u-form-item label="手机号：" borderBottom ref="item2">
					<u--input name="手机号" required placeholder="请填写手机号" v-model="registerParams.telephone"
						input-align="right" />
				</u-form-item>
				<u-form-item label="身份证号：" borderBottom ref="item3">
					<u--input name="身份证号" placeholder="身份证号" v-model="registerParams.memberCert" input-align="right" />
				</u-form-item>
				<u-form-item label="密码：" borderBottom ref="item4">
					<u--input name="密码" password required placeholder="密码" v-model="registerParams.password"
						input-align="right" />
				</u-form-item>
				<u-form-item label="会员卡类型：" borderBottom ref="item4">
					<u--input required readonly :value="value" placeholder="请选择会员卡类型" input-align="right" />
				</u-form-item>

				<u-form-item label="验证码：" borderBottom>
					<u-input placeholder="请输入短信验证码" v-model="smsValue">

						<template slot="suffix">
							<!-- <u-code ref="uCode" @change="codeChange" seconds="20" :changeText=""></u-code> -->
							<u-button @click="sendVertifyCode" :disabled="!canSend" type="primary"
								size="mini">{{sendText}}</u-button>
						</template>

					</u-input>
				</u-form-item>

			</u--form>

			<!-- 			<view @click="focusInput(5)">
				<u-cell-group>
					<u--input required center clearable type="number" @input="changeSms" input-align="right"
						:focus="focus5" label="短信验证码" placeholder="请输入短信验证码" :border="false" use-button-slot>
						<u-button slot="button" @click="sendVertifyCode" :disabled="!canSend" size="small" type="info">
							{{sendText}}
						</u-button>
					</u--input>
				</u-cell-group>
			</view> -->
			<view class="">
				<text style="font-size: 26rpx;margin-left: 20rpx;">充值金额</text>
				<view class="recharge-money">
					<text @click="clickRechargeMoney(item,index)" v-for="(item,index) in amountList"
						:class="index===currentAmount?'activeAmount':''" :key="index">{{item}}</text>
				</view>
			</view>

			<view class="card-money">
				<view>
					年费:
					<text>{{ registerParams.annualFeeMoney }}</text> 元
				</view>
				<view>
					工本费:
					<text>{{ registerParams.serviceExpense }}</text> 元
				</view>
			</view>
			<view class="pay-money" v-if="registerParams.amount==''">
				支付金额:
				<text>{{ registerParams.amount }}</text> 元
			</view>
			<view class="card-money" v-else>
				<view>
					赠送金额:
					<text>{{ registerParams.giveMoney }}</text> 元
				</view>
				<view>
					赠送券:
					<text>{{ giveCouponCount }}</text> 张
				</view>
			</view>


			<view class="confirm-agree">

				<u-checkbox-group v-model="isread">
					<u-checkbox :key="1" label="我已同意并阅读" name="我已同意并阅读"></u-checkbox>
				</u-checkbox-group>
				<text style="color: cornflowerblue;text-decoration: underline" @click="showArg= true">《会员协议》</text>
			</view>
			<u-popup :show="showArg" round='10' mode='center' @close="showArg=false">
				<view class="policy-content">
					<view class="title">
						会员政策
					</view>
					<rich-text :nodes="content"></rich-text>
					<view class="buttons">
						<u-button shape="circle" color='#999' style="margin:0 15rpx;" @click='cancelPolicy'>取消
						</u-button>
						<u-button shape="circle" type="primary" style="margin:0 15rpx;" @click='confirmPolicy'>确定
						</u-button>
					</view>
				</view>
			</u-popup>
			<view style="margin: 10px 16px 16px 16px">
				<u-button shape="circle" type="primary" block @click="checkForm">
					{{registerParams.amount==0?'确认':`确认支付${registerParams.amount}元`}}
				</u-button>
			</view>


		</view>
	</view>
</template>

<script>
	import {
		bindMemberCard,
		openCard,
		getCardPolicy,
		creatRechargeOrder,
		rechargePay,
		checkCode,
		sendCode,
		getGiveMoney,
		getGiveCoupon,
		getRechargeAmount,
		addUserInfo
	} from '../../common/http/api.js'
	import {
		checkPhone,
		checkPassword,
		checkText,
		checkId
	} from '../../common/formCheck.js'
	export default {
		data() {
			return {
				showPicker: false,
				showArg: false,
				columns: [
					[]
				],
				amountList: [],
				value: '',
				registerParams: {
					cinemaCode: this.$cinemaCode,
					openId: uni.getStorageSync("openId"),
					policyId: "",
					memberName: "",
					telephone: this.$store.state.userPhone || '',
					password: "",
					amount: 0,
					count: "1",
					rechargeType: "kkcz",
					rechargeMoney: "",
					serviceExpense: "0.00",
					annualFeeMoney: "0.00",
					memberCert: "",
					giveMoney: "0",
					giveCouponPolicyId: ''
				},
				cardFee: 0,
				policyList: [],
				minRecharge: "0.00",
				sendText: "发送验证码",
				canSend: true,
				sendCodeData: {
					openId: uni.getStorageSync("openId"),
					phone: this.$store.state.userPhone || ''
				},
				smsValue: '',
				checkStatus: false,
				timer: null,
				giveCouponCount: 0,
				isread: [],
				content: '',
				currentAmount: 0
			};
		},
		methods: {

			clickRechargeMoney(amount, index) {

				this.currentAmount = index
				this.registerParams.amount = parseFloat(this.cardFee) + parseFloat(amount)
				this.registerParams.rechargeMoney = amount
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					if (this.registerParams.policyId) this.getGiveThing()
				}, 300)

			},

			changeRecharge(e) {

				if (e.detail) {
					this.registerParams.amount = parseFloat(this.cardFee) + parseFloat(e.detail)
					this.registerParams.rechargeMoney = e.detail
					clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						if (this.registerParams.policyId) this.getGiveThing()
					}, 300)
				} else {
					this.registerParams.amount = parseFloat(this.cardFee)
					this.registerParams.rechargeMoney = 0
				}

			},

			getPolicy(id) {
				getCardPolicy().then(res => {
					const {
						cardPolicyInfos,
						code
					} = res
					if (code === "000") {
						this.policyList = cardPolicyInfos
						cardPolicyInfos.map((policy, index) => {
							if (policy.policyId == id) {
								this.value = policy.policyName
								this.content = policy.description
								this.registerParams.policyId = policy.policyId
								this.registerParams.serviceExpense = policy.openCardFee
								this.registerParams.annualFeeMoney = policy.annualFee
								this.minRecharge = policy.firstRechargeAmount
								this.registerParams.amount = parseFloat(policy.openCardFee) + parseFloat(
									policy.annualFee)
								this.cardFee = parseFloat(policy.openCardFee) + parseFloat(policy
									.annualFee)
								if (this.registerParams.rechargeMoney) this.registerParams.amount +=
									parseFloat(this.registerParams
										.rechargeMoney)
								if (this.registerParams.amount) this.getGiveThing()
							}
						})
					}
				})
			},
			getAmount(id) {
				this.amountList = []
				getRechargeAmount().then(res => {
					const {
						code,
						list
					} = res;
					if (code == '000') {
						list.find(item => {
							if (item.policyId == id && item.type == 'KKCZ') {
								for (let i = 1; i <= 6; i++) {
									if (item[`rechargeMoney${i}`]) this.amountList.push(item[
										`rechargeMoney${i}`])
								}
								this.registerParams.amount = parseFloat(this.cardFee) + parseFloat(item
									.rechargeMoney1)
								this.registerParams.rechargeMoney = item.rechargeMoney1
								clearTimeout(this.timer)
								this.timer = setTimeout(() => {
									if (this.registerParams.policyId) this.getGiveThing()
								}, 300)
							}
						})
					} else {
						uni.showToast({
							title: "获取重置金额异常",
							icon: "none"
						})
					}
				})
			},
			validateIdCard(idCard) {
				//15位和18位身份证号码的正则表达式
				let result = true
				var regIdCard =
					/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
				//如果通过该验证，说明身份证格式正确，但准确性还需计算
				if (regIdCard.test(idCard)) {
					if (idCard.length == 18) {
						var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
						var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
						var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
						for (var i = 0; i < 17; i++) {
							idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
						}
						var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
						var idCardLast = idCard.substring(17); //得到最后一位身份证号码
						//如果等于2，则说明校验码是10，身份证号码最后一位应该是X
						if (idCardMod == 2) {

							if (idCardLast == "X" || idCardLast == "x") {
								result = true
							} else {
								result = false
							}
						} else {
							//用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
							if (idCardLast == idCardY[idCardMod]) {
								result = true
							} else {
								result = false
							}
						}
					} else {
						result = false
					}
				} else {
					result = false
				}
				return result
			},
			checkForm() {
				const {
					memberName,
					telephone,
					memberCert,
					password,
					policyId,
					rechargeMoney,

				} = this.registerParams

				this.getGiveThing()
				if (!checkText(memberName)) {
					uni.showToast({
						title: "用户名不能小于四位",
						icon: "none"
					})
					return
				} else if (!checkPhone(telephone)) {
					uni.showToast({
						title: "手机号格式不正确",
						icon: "none"
					})
					return
				} else if (!checkPassword(password)) {
					uni.showToast({
						title: "密码过于简单，请重新设置",
						icon: "none"
					})
					return
				} else if (!policyId.length) {
					uni.showToast({
						title: "请选择会员卡类型",
						icon: "none"
					})
					return
				} else if (this.smsValue.length < 4) {
					uni.showToast({
						title: "请输入验证码",
						icon: "none"
					})
					return
				} else if (parseFloat(rechargeMoney) < parseFloat(this.minRecharge)) {
					uni.showToast({
						title: `充值金额不能小于${this.minRecharge}元`,
						icon: "none"
					})
					return
				} else if (this.isread.length == 0) {
					uni.showToast({
						title: `请阅读会员协议`,
						icon: "none"
					})
					this.showArg = true;
					return
				} else if (memberCert.length > 0 && !this.validateIdCard(memberCert)) {
					uni.showToast({
						title: `请输入正确身份证`,
						icon: "none"
					})
					return
				}
				this.checkVertifyCode()

			},
			registerCard() {
				uni.showLoading({
					title: "开卡中"
				})
				if (parseFloat(this.registerParams.amount) == 0) {
					openCard(this.registerParams).then(res => {
						if (res.code == "000") {
							addUserInfo({
								name: this.registerParams.memberName,
								phoneNo: this.registerParams.telephone,
								openId: uni.getStorageSync("openId"),
							})
							this.$toast("开卡成功");
							const {
								data
							} = res;
							post("/member/v1/bindMemberCard", {
								cardCode: data.cardCode,
								openId: uni.getStorageSync("openId"),
							}).then((res) => {
								uni.hideLoading()
								uni.redirectTo({
									url: "../cardList/cardList"
								})
							});
						}
					})
				} else {
					creatRechargeOrder(this.registerParams).then(res => {
						const {
							data: {
								orderNo
							}
						} = res
						rechargePay({
							orderNo: orderNo,
							openId: uni.getStorageSync("openId")
						}).then(res => {
							const {
								data
							} = res;
							uni.requestPayment({
								timeStamp: data.timeStamp,
								nonceStr: data.nonceStr,
								package: data.package,
								signType: data.signType,
								paySign: data.paySign,
								appId: data.appId,
								success: res => {
									addUserInfo({
										name: this.registerParams.memberName,
										phoneNo: this.registerParams.telephone,
										openId: uni.getStorageSync("openId"),
									})
									if (res.errMsg === "requestPayment:ok") {
										uni.showToast({
											title: "开卡成功",
											icon: "none",
											duration: 1500
										})
										uni.hideLoading()
									}
									setTimeout(() => {
										uni.redirectTo({
											url: "../cardList/cardList"
										})
									}, 1500)
								},
								fail: err => {
									console.log(err)
								}
							})
						})
					})
				}
			},
			sendVertifyCode() {
				this.canSend = false
				let time = 30
				const timer = setInterval(() => {
					time--;
					this.sendText = `${time}后重新发送`
					if (time == 0) {
						this.canSend = true
						this.sendText = "发送验证码"
						clearInterval(timer)
					}
				}, 1000)
				sendCode(this.sendCodeData).then(res => {
					const {
						code
					} = res
					if (code === "SUCCESS") {
						uni.showToast({
							title: "验证码已发送",
							icon: "none"
						})
					}
				})
			},
			checkVertifyCode() {
				checkCode({
					...this.sendCodeData,
					smsValue: this.smsValue
				}).then(res => {
					const {
						code,
						msg
					} = res
					if (code === "FAIL") {
						uni.showToast({
							title: msg,
							icon: 'none'
						})
					} else if (code === "SUCCESS") {

						this.registerCard()
					}
				})
			},
			getGiveThing() {
				getGiveMoney(this.registerParams).then(res => {
					const {
						data
					} = res
					if (data) {
						this.registerParams.giveMoney = data.giveMoney
					} else {
						this.registerParams.giveMoney = '0'
					}
				})
				getGiveCoupon(this.registerParams).then(res => {
					const {
						data
					} = res
					if (data) {
						this.giveCouponCount = data.giveCount
						this.registerParams.giveCouponPolicyId = data.giveCouponPolicyId
					} else {
						this.giveCouponCount = '0'
						this.registerParams.giveCouponPolicyId = ''

					}

				})
			},
			cancelPolicy() {
				this.showArg = false
				this.isread = false
			},
			confirmPolicy() {
				this.showArg = false
				this.isread = true
			}
		},
		onLoad(options) {
			this.getPolicy(options.id)
			this.getAmount(options.id)
			uni.setNavigationBarTitle({
				title: this.$store.state.cinemaName
			})

			this.registerParams.openId = uni.getStorageSync("openId");
		}
	}
</script>

<style lang="scss">
	.custom-class {
		width: 120rpx;
	}

	.card-money {
		display: flex;
		justify-content: space-between;
		padding: 10rpx 30rpx;
		font-size: 28rpx;
		margin-top: 15rpx;

		text {
			color: red;
		}
	}

	.pay-money {
		// width: 100vw;
		padding-right: 30rpx;
		margin-top: 15rpx;
		text-align: right;

		text {
			color: red;
		}
	}

	.confirm-agree {
		margin-top: 80rpx;
		font-size: 24rpx;
		padding-left: 30rpx;
		display: flex;
		align-items: center;
	}

	.policy-content {
		width: 80vw;
		padding: 20rpx 30rpx 100rpx 30rpx;
		min-height: 350rpx;
		max-height: 600rpx;
		position: relative;

		.title {
			text-align: center;
			font-size: 30rpx;
			font-weight: bold;
		}

		.content {
			font-size: 26rpx;
			text-align: justify;
		}

		.buttons {
			position: absolute;
			bottom: 0;
			height: 100rpx;
			width: calc(100% - 60rpx);
			display: flex;
			align-items: center;
			justify-content: center;

			button {
				width: 120rpx !important;
			}
		}
	}

	.recharge-money {
		width: 94vw;
		margin: auto;
		display: flex;
		flex-wrap: wrap;

		text {
			border: 1px solid #f0f0f5;
			display: block;
			padding: 10rpx 20rpx;
			width: 120rpx;
			text-align: center;
			color: #007AFF;
			font-size: 28rpx;
			margin: 10rpx 0 0 50rpx;
		}

		.activeAmount {
			border: 1px solid #007AFF;
		}
	}
</style>